package uk.ac.durham.tel.synergynet.covanto.workspace.ui.dialogs;

import java.lang.reflect.InvocationTargetException;

import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.wizard.Wizard;
import org.eclipse.ui.INewWizard;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.actions.WorkspaceModifyOperation;

import uk.ac.durham.tel.synergynet.covanto.workspace.WorkspaceController;
import uk.ac.durham.tel.synergynet.covanto.workspace.WorkspaceException;

public class CreateProjectWizard extends Wizard implements INewWizard {
	NewProjectInfomationWizardPage newProjectInfomationWizardPage;
	
	@Override
	public void addPages() {
		super.addPages();
		newProjectInfomationWizardPage = new NewProjectInfomationWizardPage("New Study Information");
		this.addPage(newProjectInfomationWizardPage);
	}
	
	@Override
	public void init(IWorkbench workbench, IStructuredSelection selection) {
		//
	}

	@Override
	public boolean performFinish() {
		boolean projectCreated = createProject();
		return projectCreated;
	}

	private boolean createProject() {
		final StringBuilder errorMessages = new StringBuilder();
		try {
			WorkspaceModifyOperation op = new WorkspaceModifyOperation() {
				@Override
				protected void execute(IProgressMonitor monitor)
						throws CoreException, InvocationTargetException,
						InterruptedException {
					try {
						WorkspaceController.getInstance().createProject(newProjectInfomationWizardPage.getNewProjectName(), monitor);
					} catch (WorkspaceException e) {
						errorMessages.append(e.getMessage());
					}
				}
			};
			this.getContainer().run(false, false, op);
			if (errorMessages.toString().compareTo("")!=0)
				throw new Exception(errorMessages.toString());
		} catch (Exception ex) {
			MessageDialog.openError(this.getShell(), "Error", ex.getMessage());
			return false;
		}
		return true;
	}

}
